#!/bin/bash
#
# Copyright (C) 2024, 2025, Cyrus Li (e21920076@126.com). All rights reserved.
#

#
# A handy script to help clean /var/tmp and /tmp
#

# XXX: sub-dirs under /var/tmp/ which must be reserved
VT_RSV_DIRS=${VT_RSV_DIRS:-"sandbox,huanian,lijing,hnli"}

# XXX: always output colorful string
export ISATTY=yes

function print { echo -e "$*"; }

function _isatty
{
    typeset -l isatty=${ISATTY:-"auto"}
    [[ $isatty == "yes" ]] && return 0         # yes
    [[ $isatty == "no"  ]] && return 1         # no
    [[ -t 1 && -t 2 ]] && return 0 || return 1 # auto
}

function str2gray    { _isatty && print "\033[1;30m$@\033[m" || print "$@"; }
function str2red     { _isatty && print "\033[1;31m$@\033[m" || print "$@"; }
function str2green   { _isatty && print "\033[1;32m$@\033[m" || print "$@"; }
function str2yellow  { _isatty && print "\033[1;33m$@\033[m" || print "$@"; }
function str2blue    { _isatty && print "\033[1;34m$@\033[m" || print "$@"; }
function str2magenta { _isatty && print "\033[1;35m$@\033[m" || print "$@"; }
function str2cyan    { _isatty && print "\033[1;36m$@\033[m" || print "$@"; }
function str2white   { _isatty && print "\033[1;37m$@\033[m" || print "$@"; }

function getPS1
{
    echo "$(id -un)@$(hostname):$(pwd -P)"
}

function enter_dir
{
    typeset dir=${1?"*** what dir"}
    pushd $(pwd -P) > /dev/null 2>&1
    cd $dir
}

function leave_dir
{
    popd > /dev/null 2>&1
}

function do_ls_l
{
    echo "$(str2cyan $(getPS1))$(str2red \$) $(str2yellow ls --color -l)"
    ls --color -l
    echo
}

function is_reserved
{
    typeset dir="$1"
    typeset reserved_dirs="$2"
    for rsv_dir in $(echo $reserved_dirs | tr ',' ' '); do
        [[ $dir == $rsv_dir ]] && return 0
    done
    return 1
}


enter_dir "/var/tmp"
for i in $(ls -1); do
    is_reserved "$i" "$VT_RSV_DIRS" && continue
    echo "Remove /var/tmp/$i ..."
    sudo rm -rf /var/tmp/$i
done
do_ls_l
leave_dir

if [[ $1 == "-v" ]]; then
    sudo rm -rf /tmp/*
    enter_dir "/tmp"
    do_ls_l
    leave_dir
fi
